# -*- coding: utf-8 -*-

import logging

from odoo.http import request

from odoo_contrib import http as contrib_http
from odoo_contrib.marshal import marshal_with
from odoo_contrib.parser import parse_with

from ..schemas import marshals
from ..schemas import parsers
from ..utils.auth import current_user

logger = logging.getLogger(__name__)


@contrib_http.route('/wechat')
class UserProfile(contrib_http.Controller):
    @contrib_http.route('/user/profile', methods=['GET'])
    @marshal_with(marshals.WechatUserSchema, envelope='data')
    def detail(self, **kwargs):
        return current_user

    @contrib_http.route('/user/profile', methods=['PUT'])
    @parse_with(parsers.WechatUserParser)
    @marshal_with(marshals.WechatUserSchema, envelope='data')
    def update(self, **kwargs):
        info = self.parser.parse()
        encrypted_data = info.pop('encrypted_data', None)
        iv = info.pop('iv', None)
        info = {k: v for k, v in info.items() if v}
        if encrypted_data and iv:
            decrypted = request.miniapp.decrypt_user_info(
                current_user.session_key,
                iv,
                encrypted_data
            )
            logger.info('Decrypted user info: %s', decrypted)
            if 'nickName' in decrypted and decrypted['nickName']:
                info['nickname'] = decrypted['nickName']
            if 'gender' in decrypted and decrypted['gender']:
                info['gender'] = decrypted['gender']
            if 'language' in decrypted and decrypted['language']:
                info['language'] = decrypted['language']
            if 'city' in decrypted and decrypted['city']:
                info['city'] = decrypted['city']
            if 'province' in decrypted and decrypted['province']:
                info['province'] = decrypted['province']
            if 'country' in decrypted and decrypted['country']:
                info['country'] = decrypted['country']
            if 'avatarUrl' in decrypted and decrypted['avatarUrl']:
                info['avatar'] = decrypted['avatarUrl']
            if 'phoneNumber' in decrypted and decrypted['phoneNumber']:
                info['mobile'] = decrypted['phoneNumber']
        current_user.update_profile(**info)
        return current_user
